package chapter07

/**
  * create by undeRdoG on  2021-06-05  23:57
  * 凡心所向，素履以往，生如逆旅，一苇以航。
  */
object Test14_HighLevelFunction_Map {

  def main(args: Array[String]): Unit = {
    val list = List(1,2,3,4,5,6,7,8,9)

    // filter   选取偶数
    val ints: List[Int] = list.filter(_ %2 ==0)
    println(ints)
    println("==================================================================================================")

    // map 操作   把集合中每个数乘2
    println(list.map(_ * 2))

    // 扁平化
    val nestedList: List[List[Int]] = List(List(1,2,3),List(4,5),List(6,7,8,9))

    val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)

    val flatList2 = nestedList.flatten

    println(flatList)
    println(flatList2)

    // 扁平映射
    // 将一组字符串分词，并保存成单词的列表
    val strings: List[String] = List("hello world","hello scala","hello java","we study")

    val res: List[String] = strings.flatMap(_.split(" "))
    println(res)

    // 分组操作 groupBy
    list.groupBy(x => x % 2)
    val resMap: Map[Int, List[Int]] = list.groupBy(_ % 2)
    println(resMap)


    // 一组词汇，按照首字母归类
    val word = List("china","america","alice","canada","japan")
    val charToStrings: Map[Char, List[String]] = word.groupBy(_.charAt(0))
    println(charToStrings)
  }
}
